<script setup lang="ts">
  import { ref, watch, reactive, computed } from 'vue';
  import {
    wmsDeliveryTicketSend,
    wmsDeliveryTicketDataChanged,
    wmsDeliveryTicketStatusChanged,
  } from '@/api/operation-monitoring';
  import { Notification } from '@arco-design/web-vue';

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接状态',
      dataIndex: 'deliveryStatus',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '条码',
      dataIndex: 'barcode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '成品型号',
      dataIndex: 'mProductNumber',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '物料名称',
      dataIndex: 'itemName',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单号',
      dataIndex: 'deliveryPlanCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '移交数量',
      dataIndex: 'deliveryQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '接收数量',
      dataIndex: 'storageQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '移交人',
      dataIndex: 'deliveryEmpCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '移交时间',
      dataIndex: 'deliveryDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '机型',
      dataIndex: 'productCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '批次',
      dataIndex: 'batchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '起始架次',
      dataIndex: 'startLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '截止架次',
      dataIndex: 'endLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '合格证号',
      dataIndex: 'mesCheckQualiticationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '限用机型',
      dataIndex: 'xProductCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '限用批次',
      dataIndex: 'xLimitBatchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '限用架次',
      dataIndex: 'xLimitLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单ID',
      dataIndex: 'wmsDeliveryPlanId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '交接单状态',
      dataIndex: 'deliveryStatusCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  // 创建一个响应式的本地副本
  const localTableData = ref<any>();
  // 数据库一共有多少条
  const total = ref<number>(1);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const rangeDate = ref<Date[]>([]);
  const selectedKeys = ref<string[]>();
  const rowSelection = reactive({
    type: 'checkbox' as 'checkbox' | 'radio',
    showCheckedAll: true,
  });
  // 计算已选择的表格数据
  const selectedTableData = computed(() => {
    return localTableData.value.filter((item: any) =>
      selectedKeys.value?.includes(item.PAGEHELPER_ROW_ID)
    );
  });
  const formValues = reactive({
    barcode: '',
    itemCode: '',
    mProductNumber: '',
    qualityCode: '',
    deliveryStatus: '',
    deliveryPlanCode: '',
    deliveryOrgCode: '',
    receiveOrgCode: '',
    productCode: '',
    batchNo: '',
    startLotNo: '',
    endLotNo: '',
    startTime: '',
    endTime: '',
  });
  const form = reactive({
    barcode: '',
    mesCheckQualiticationId: '',
    productCode: '',
    startLotNo: '',
    endLotNo: '',
    qualityCode: '',
    applyItemCode: '',
    deliveryPlanCode: '',
    deliveryStatusCode: '',
  });
  const randomNum = ref<number>();
  const validateNum = ref<number>();
  const dataModalVisible = ref<boolean>(false);
  const statusModalVisible = ref<boolean>(false);
  const validateModalVisible = ref<boolean>(false);
  async function handleSearch() {
    const response = await wmsDeliveryTicketSend({
      searchParams: formValues,
      pageParameter: { page: pageNum.value, rows: pageSize.value },
    });
    if (response.retCode === '200') {
      localTableData.value = response.responseBody.result;
      total.value = response.responseBody.pageParameter.totalCount;
    } else {
      Notification.warning({
        title: '提示',
        content: '查询失败',
        closable: true,
      });
    }
  }
  function reset() {
    Object.keys(formValues).forEach((key) => {
      (formValues as Record<string, any>)[key] = '';
    });
    rangeDate.value = [];
    setTimeout(() => {
      handleSearch();
    }, 150);
  }
  async function validateModalOk() {
    if (validateNum.value !== randomNum.value) {
      Notification.error({
        title: '提示',
        content: '验证失败',
        closable: true,
      });
      return;
    }
    // 验证通过后清除已选择
    selectedKeys.value = [];
    // 修改交接单数据
    if (randomNum.value && randomNum.value <= 50) {
      const response = await wmsDeliveryTicketDataChanged(form);
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: `${response.message}`,
          closable: true,
        });
        handleSearch();
      } else {
        Notification.error({
          title: '失败',
          content: `${response.message ? response.message : '修改失败'}`,
          closable: true,
        });
      }
    }
    // 修改交接单状态
    if (randomNum.value && randomNum.value >= 51) {
      const response = await wmsDeliveryTicketStatusChanged(form);
      if (response.retCode === '200') {
        Notification.success({
          title: '成功',
          content: `${response.message}`,
          closable: true,
        });
        handleSearch();
      } else {
        Notification.error({
          title: '失败',
          content: `${response.message ? response.message : '修改失败'}`,
          closable: true,
        });
      }
    }
  }

  function modalCancel() {
    statusModalVisible.value = false;
    dataModalVisible.value = false;
  }
  function modalOpen(item: number) {
    if (selectedKeys.value?.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请选择一条数据',
        closable: true,
      });
    } else {
      switch (item) {
        case 1:
          dataModalVisible.value = true;
          Object.assign(form, selectedTableData.value[0]);
          break;
        case 2:
          statusModalVisible.value = true;
          Object.assign(form, selectedTableData.value[0]);
          break;
        default:
      }
    }
  }
  function modalOk(item: number) {
    // 10-50的随机数
    if (item === 1) {
      randomNum.value = Math.floor(Math.random() * (50 - 10 + 1)) + 10;
      validateNum.value = undefined;
      validateModalVisible.value = true;
    }
    // 51-99的随机数
    if (item === 2) {
      randomNum.value = Math.floor(Math.random() * (99 - 51 + 1)) + 51;
      validateNum.value = undefined;
      validateModalVisible.value = true;
    }
  }
  // 监听页面变化
  watch([pageNum, pageSize], () => {
    handleSearch();
  });
  watch(rangeDate, () => {
    if (rangeDate.value && rangeDate.value.length >= 2) {
      formValues.startTime = rangeDate.value[0].toString();
      formValues.endTime = rangeDate.value[1].toString();
    }
  });
  // 监听已选择数据的序号，并更新到已选择表格数据行字段
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
</script>

<template>
  <div class="content-page">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-input
          v-model="formValues.barcode"
          placeholder="条码"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.itemCode"
          placeholder="图号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.mProductNumber"
          placeholder="成品型号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.qualityCode"
          placeholder="质量编号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.deliveryPlanCode"
          placeholder="交接单号"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.deliveryOrgCode"
          placeholder="移交单位简码"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.receiveOrgCode"
          placeholder="接收单位简码"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.productCode"
          placeholder="机型"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.batchNo"
          placeholder="批次"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.startLotNo"
          placeholder="起始架次"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-input
          v-model="formValues.endLotNo"
          placeholder="截止架次"
          size="large"
          @press-enter="handleSearch"
        />
      </a-col>
      <a-col :span="6">
        <a-select
          v-model="formValues.deliveryStatus"
          placeholder="交接状态"
          default-value=""
          @press-enter="handleSearch"
        >
          <a-option value="1">未确认</a-option>
          <a-option value="2">已移交</a-option>
          <a-option value="3">待入库</a-option>
          <a-option value="6">已入库</a-option>
          <a-option value="7">已退回</a-option>
        </a-select>
      </a-col>
      <a-col :span="12">
        <a-range-picker v-model:model-value="rangeDate" style="width: auto" />
      </a-col>
    </a-row>
    <a-space style="margin-top: 16px">
      <a-button type="primary" size="large" @click="handleSearch">
        查询
      </a-button>
      <a-button size="large" @click="reset">重置</a-button>
      <a-button type="outline" size="large" @click="modalOpen(1)">
        修改交接单数据
      </a-button>
      <a-button type="outline" size="large" @click="modalOpen(2)">
        修改交接单状态
      </a-button>
    </a-space>
    <a-divider />
    <div>
      <a-table
        v-model:selected-keys="selectedKeys"
        :stripe="true"
        class="top-table"
        :pagination="false"
        :columns="columns"
        :data="localTableData"
        :row-selection="rowSelection"
        row-key="PAGEHELPER_ROW_ID"
      >
      </a-table>
      <div class="page-position">
        <a-pagination
          :total="total"
          :current="pageNum"
          :page-size="pageSize"
          show-total
          show-jumper
          show-page-size
          @change="change"
          @update:page-size="changeSize"
        />
      </div>
    </div>
  </div>
  <a-modal
    v-model:visible="dataModalVisible"
    @ok="modalOk(1)"
    @cancel="modalCancel"
  >
    <template #title> 交接单数据修改 </template>
    <a-space direction="vertical" fill>
      <a-form :model="form">
        <a-form-item field="barcode" label="条码">
          <a-input v-model="form.barcode"></a-input>
        </a-form-item>
        <a-form-item field="mesCheckQualiticationId" label="合格证号">
          <a-input v-model="form.mesCheckQualiticationId"></a-input>
        </a-form-item>
        <a-form-item field="productCode" label="机型">
          <a-input v-model="form.productCode"></a-input>
        </a-form-item>
        <a-form-item field="startLotNo" label="开始架次">
          <a-input v-model="form.startLotNo"></a-input>
        </a-form-item>
        <a-form-item field="endLotNo" label="结束架次">
          <a-input v-model="form.endLotNo"></a-input>
        </a-form-item>
        <a-form-item field="qualityCode" label="质量编号">
          <a-input v-model="form.qualityCode"></a-input>
        </a-form-item>
        <a-form-item field="applyItemCode" label="标准件计划图号">
          <a-input v-model="form.applyItemCode"></a-input>
        </a-form-item>
      </a-form>
    </a-space>
  </a-modal>
  <a-modal
    v-model:visible="statusModalVisible"
    @ok="modalOk(2)"
    @cancel="modalCancel"
  >
    <template #title> 交接单状态修改 </template>
    <a-space direction="vertical" fill>
      <a-form :model="form">
        <a-form-item label="交接单号">
          <a-input v-model="form.deliveryPlanCode"></a-input>
        </a-form-item>
        <a-form-item label="交接单状态">
          <a-input v-model="form.deliveryStatusCode"></a-input>
        </a-form-item>
      </a-form>
    </a-space>
  </a-modal>
  <a-modal
    v-model:visible="validateModalVisible"
    @ok="validateModalOk"
    @cancel="() => (validateModalVisible = false)"
  >
    <template #title> 验证提示 </template>
    <div style="font-size: large">
      请输入:
      <span class="validate-font">{{ randomNum }}</span>
    </div>
    <a-input-number v-model:model-value="validateNum"></a-input-number>
  </a-modal>
</template>

<style scoped>
  span {
    margin-bottom: 16px;
  }
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .content-page {
    padding-left: 12px;
    padding-right: 12px;
  }
  .validate-font {
    font-size: larger;
    font-weight: bolder;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  }
</style>
